const { validationResult } = require('express-validator');
const { Favorate, Video } = require('../models');

class FavoriteController {
  // 视频收藏/取消收藏
  static async toggleVideoFavorite(req, res) {
    try {
      const videoId = req.params.videoId;
      const userId = req.user.id;
      
      // 检查视频是否存在
      const video = await Video.findByPk(videoId);
      if (!video) {
        return res.status(404).json({ success: false, message: '视频不存在' });
      }
      
      // 切换收藏状态
      const result = await Favorate.toggleFavorite(userId, videoId);
      
      res.json({ 
        success: true, 
        message: result.favorited ? '收藏成功' : '取消收藏成功',
        data: {
          favorited: result.favorited,
          favoriteCount: result.favoriteCount
        }
      });
    } catch (error) {
      console.error('操作视频收藏失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  

  // 检查用户是否收藏了视频
  static async checkVideoFavorite(req, res) {
    try {
      const videoId = req.params.videoId;
      const userId = req.user.id;
      
      // 检查视频是否存在
      const video = await Video.findByPk(videoId);
      if (!video) {
        return res.status(404).json({ success: false, message: '视频不存在' });
      }
      
      const favorited = await Favorate.isFavorited(userId, videoId);
      const favoriteCount = await Favorate.count({ where: { video_id: videoId } });
      
      res.json({ 
        success: true, 
        data: {
          favorited,
          favoriteCount
        }
      });
    } catch (error) {
      console.error('检查视频收藏状态失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 批量检查视频收藏状态
  static async batchCheckVideoFavorite(req, res) {
    try {
      const { videoIds } = req.body;
      const userId = req.user.id;
      
      if (!Array.isArray(videoIds)) {
        return res.status(400).json({ success: false, message: 'videoIds必须是数组' });
      }
      
      const results = await Favorate.batchCheckFavorited(userId, videoIds);
      
      res.json({ 
        success: true, 
        data: results
      });
    } catch (error) {
      console.error('批量检查视频收藏状态失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 批量收藏视频
  static async batchFavoriteVideos(req, res) {
    try {
      const { videoIds } = req.body;
      const userId = req.user.id;
      
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({ success: false, message: '验证失败', errors: errors.array() });
      }
      
      if (!Array.isArray(videoIds) || videoIds.length === 0) {
        return res.status(400).json({ success: false, message: 'videoIds必须是非空数组' });
      }
      
      // 限制批量操作数量
      if (videoIds.length > 50) {
        return res.status(400).json({ success: false, message: '批量操作数量不能超过50个' });
      }
      
      // 检查视频是否存在
      const existingVideos = await Video.findAll({ 
        where: { id: videoIds },
        attributes: ['id']
      });
      
      const existingVideoIds = existingVideos.map(v => v.id);
      const validVideoIds = videoIds.filter(id => existingVideoIds.includes(id));
      
      if (validVideoIds.length === 0) {
        return res.status(404).json({ success: false, message: '没有找到有效的视频' });
      }
      
      // 批量创建收藏记录
      const createdCount = await Favorate.batchCreateFavorites(userId, validVideoIds);
      
      res.json({ 
        success: true, 
        message: `成功收藏 ${createdCount} 个视频`,
        data: {
          createdCount,
          totalRequested: videoIds.length,
          validVideoIds
        }
      });
    } catch (error) {
      console.error('批量收藏视频失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 批量取消收藏视频
  static async batchUnfavoriteVideos(req, res) {
    try {
      const { videoIds } = req.body;
      const userId = req.user.id;
      
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({ success: false, message: '验证失败', errors: errors.array() });
      }
      
      if (!Array.isArray(videoIds) || videoIds.length === 0) {
        return res.status(400).json({ success: false, message: 'videoIds必须是非空数组' });
      }
      
      // 限制批量操作数量
      if (videoIds.length > 50) {
        return res.status(400).json({ success: false, message: '批量操作数量不能超过50个' });
      }
      
      // 批量删除收藏记录
      const deletedCount = await Favorate.batchDeleteFavorites(userId, videoIds);
      
      res.json({ 
        success: true, 
        message: `成功取消收藏 ${deletedCount} 个视频`,
        data: {
          deletedCount
        }
      });
    } catch (error) {
      console.error('批量取消收藏视频失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 清空用户收藏（谨慎使用）
  static async clearUserFavorites(req, res) {
    try {
      const userId = req.user.id;
      
      // 删除用户所有收藏
      const deletedCount = await Favorate.destroy({ where: { user_id: userId } });
      
      res.json({ 
        success: true, 
        message: `成功清空 ${deletedCount} 个收藏记录`,
        data: {
          deletedCount
        }
      });
    } catch (error) {
      console.error('清空用户收藏失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }
}

module.exports = FavoriteController;